<template>
  <div class="data-panel">
    <!-- 面板头部 -->
    <!-- <div class="panel-header">
      <div class="header-content">
        <h1 class="panel-title">题库</h1>
        <p class="panel-subtitle">管理您的题目库和练习内容</p>
      </div>
    </div> -->

    <!-- 选择题库的模态框 -->
    <SelectBankModal
      ref="selectBankModal"
      :questionBanks="questionBanks"
      @load-more="loadMoreBanks"
      @confirm="handleBankSelection"
    />

    <!-- 题库类型配置模态框 -->
    <TypeConfigModal ref="typeConfigModal" />

    <!-- 题库类型配置模态框 -->
    <QuestionTypeConfigModal ref="questionTypeConfigModal" />

    <!-- 子路由显示区域 -->
    <router-view />
  </div>
</template>

<script>
// 引入选择题库的模态框
import SelectBankModal from "@/components/questionbank/SelectBankModal.vue";
// 引入题库类型配置模态框
import TypeConfigModal from "@/components/questionbank/TypeConfigModal.vue";
// 引入题库类型配置模态框
import QuestionTypeConfigModal from "@/components/questionbank/QuestionTypeConfigModal.vue";
// 引入题库API
import { getQuestionBankList } from "@/api/question";

import { mapGetters } from "vuex";

export default {
  name: "DataPanel",
  components: {
    SelectBankModal,
    TypeConfigModal,
    QuestionTypeConfigModal,
  },
  data() {
    return {
      questionBanks: [], // 题库列表
      // 分页参数
      pagination: {
        pageNum: 1,
        pageSize: 999,
        hasMore: true,
        bankName: "", // 搜索关键词
      },
      loading: false,
      // 预览题目数据
      previewData: null,
    };
  },
  created() {
    this.$registerWebSocketHandler(this.handleMessage);
    // 初始加载题库数据
    this.fetchQuestionBanks();
  },
  beforeDestroy() {
    // Clean up WebSocket handler when component is destroyed
    if (this.$unregisterWebSocketHandler) {
      this.$unregisterWebSocketHandler(this.handleMessage);
    }
  },
  methods: {
    // 处理websocket发送来的消息的方法
    handleMessage(message) {
      // console.log("DataPanel处理消息：", message);

      // 添加定时器
      setTimeout(() => {
        // 空执行
        switch (message.messageType) {
          case 50: // 打开题库配置框
            if (this.$refs.typeConfigModal) {
              this.$refs.typeConfigModal.show();
            } else {
              console.warn("TypeConfigModal ref is not available");
              // Queue the operation for next tick to ensure component is mounted
              this.$nextTick(() => {
                if (this.$refs.typeConfigModal) {
                  this.$refs.typeConfigModal.show();
                } else {
                  console.error(
                    "TypeConfigModal is still not available after nextTick"
                  );
                }
              });
            }
            break;
          case 51: // 接收题目预览数据
            // 跳转结果生成页面并且 接收消息
            console.log("message.content", message.content);

            this.$router.push({
              name: "AiBankResultHeader",
              params: { data: message.content },
            });
            break;
          case 52:
            // 跳转到题库列表页面
            this.$router.push("/question-bank");
            // 刷新页面
            this.fetchQuestionBanks();
            // 提示用户保存成功
            this.$message({
              type: "success",
              message: "题目保存成功",
              duration: 1500,
            });
            break;
          case 53: // 打开选择题库模态框
            this.ensureDataAndOpenModal();
            break;
          case 54: // 没有题库
            if (this.$refs.questionTypeConfigModal) {
              this.$refs.questionTypeConfigModal.show();
            } else {
              console.warn("QuestionTypeConfigModal ref is not available");
              this.$nextTick(() => {
                if (this.$refs.questionTypeConfigModal) {
                  this.$refs.questionTypeConfigModal.show();
                } else {
                  console.error(
                    "QuestionTypeConfigModal is still not available after nextTick"
                  );
                }
              });
            }
            break;
          case 55: // 接收最新生成的题目
            // 通过 Vuex 存储重新生成的题目
            this.$store.commit(
              "question/UPDATE_REGENERATED_QUESTION",
              JSON.parse(message.content)
            );
            break;
          case 56: // 回到主页
            this.$router.push("/question-bank");
            break;
          case 57: // 刷新页面完成
            this.$router.push("/question-bank/bank-list");
            this.fetchQuestionBanks();
            break;
          case 58: // 跳转到试卷页面
            this.$router.push("/paper-index");
            break;
          case 59: // 搜索题库，接收搜索的关键词
            const searchKeyword = message.content;

            // 创建一个独立的搜索处理方法
            this.handleBankSearch(searchKeyword);
            break;
          default:
            console.warn("未知消息类型:", message.type);
        }
      }, 1500);
    },
    // 确保数据加载后打开模态框的方法
    ensureDataAndOpenModal() {
      if (this.loading) {
        // console.log('数据正在加载中，等待加载完成后再打开模态框');
        // 数据加载中，等待完成后再打开
        const checkAndOpen = () => {
          if (!this.loading) {
            this.openSelectBankModal();
          } else {
            setTimeout(checkAndOpen, 100);
          }
        };
        setTimeout(checkAndOpen, 100);
        return;
      }

      if (this.questionBanks.length === 0) {
        // console.log('题库数据为空，先加载数据');
        // 如果没有数据，先加载数据
        this.pagination.pageNum = 1; // 重置分页
        this.fetchQuestionBanks().then(() => {
          // console.log('数据加载完成，开始打开模态框');
          this.openSelectBankModal();
        });
      } else {
        // console.log('已有题库数据，直接打开模态框');
        this.openSelectBankModal();
      }
    },

    // 获取题库数据
    async fetchQuestionBanks() {
      if (this.loading || !this.pagination.hasMore) return;

      this.loading = true;
      try {
        const res = await getQuestionBankList({
          pageNum: this.pagination.pageNum,
          pageSize: this.pagination.pageSize,
          bankName: this.pagination.bankName || "",
        });

        const { code, data } = res.data;

        if (code === 200) {
          // 首次加载替换数据，后续加载追加数据
          if (this.pagination.pageNum === 1) {
            this.questionBanks = data.rows;
          } else {
            this.questionBanks = [...this.questionBanks, ...data.rows];
          }

          // 判断是否还有更多数据
          this.pagination.hasMore = this.questionBanks.length < data.total;
          this.pagination.pageNum++;
        }
      } catch (error) {
        // console.error('获取题库数据失败:', error);
      } finally {
        this.loading = false;
      }
    },
    // 加载更多题库数据
    loadMoreBanks() {
      // console.log('父组件接收到加载更多请求');
      return this.fetchQuestionBanks()
        .then(() => {
          // console.log('加载完成，当前题库数量:', this.questionBanks.length);
        })
        .catch((err) => {
          // console.error('加载更多题库失败:', err);
        });
    },

    // 刷新题库数据
    refreshBanks() {
      this.pagination.pageNum = 1;
      this.pagination.hasMore = true;
      this.fetchQuestionBanks();
    },

    // 处理题库选择确认
    handleBankSelection(selection) {
      // console.log('选中的题库:', selection);
      // 获取选中的题库ID和详细信息
      const { bankId, bank } = selection;

      // 这里处理单个选中题库的逻辑
      if (bankId && bank) {
        // 例如：可以导航到题库详情页
        this.$router.push(`/question-bank/detail/${bankId}`);
        // 或者打开题库相关操作
        // this.$emit('bank-selected', bank);
      }
    },

    // 打开选择题库的模态框
    openSelectBankModal() {
      // console.log('尝试打开选择题库模态框');

      // 确保数据已加载
      if (this.questionBanks.length === 0) {
        // console.log('题库数据为空，先加载数据');
        this.fetchQuestionBanks()
          .then(() => {
            // console.log('数据加载完成，准备打开模态框');
            this.actuallyOpenModal();
          })
          .catch((err) => {
            // console.error('加载题库数据失败:', err);
            this.$message.error("加载题库数据失败，请刷新页面重试");
          });
      } else {
        // console.log('已有题库数据，直接打开模态框');
        this.actuallyOpenModal();
      }
    },

    // 实际打开模态框的方法
    actuallyOpenModal() {
      // 在下一个DOM更新周期尝试打开模态框
      this.$nextTick(() => {
        // 确保模态框引用存在
        if (this.$refs.selectBankModal) {
          // console.log('模态框引用存在，调用open方法');
          // 安全地调用open方法
          try {
            this.$refs.selectBankModal.open();
            // console.log('模态框已成功打开');
          } catch (error) {
            // console.error('打开模态框时出错:', error);
            // this.$message.error('打开题库选择窗口失败，请刷新页面重试');
          }
        } else {
          // console.error('找不到selectBankModal的引用');
          // this.$message.error('无法找到题库选择窗口，请刷新页面重试');
        }
      });
    },

    /**
     * 处理题库搜索
     * @param {String} keyword - 搜索关键词
     */
    handleBankSearch(keyword) {
      // 如果SelectBankModal处于打开状态，将搜索请求发送到模态框
      if (this.$refs.selectBankModal && this.$refs.selectBankModal.visible) {
        // 设置模态框的搜索关键词并触发搜索
        this.$refs.selectBankModal.searchQuery = keyword;
        this.$refs.selectBankModal.handleSearch();
        return;
      }

      // 模态框未打开，执行全局搜索

      this.$store.commit("question/SET_PAGINATION", {
        bankName: keyword,
        currentPage: 1,
      });
      this.$store.dispatch("question/fetchBanks");
    },
  },
};
</script>

<style lang="less" scoped>
@import "@/styles/variables.less";

.data-panel {
  flex: 1;
  padding: 2rem;
  background-color: @gray-50;
  overflow-y: auto;
  scroll-behavior: smooth;
  display: flex;
  flex-direction: column;

  &::-webkit-scrollbar {
    width: 5px;
  }

  &::-webkit-scrollbar-track {
    background: transparent;
    margin: 4px 0;
    border-radius: 10px;
  }

  &::-webkit-scrollbar-thumb {
    background: linear-gradient(
      to bottom,
      rgba(@primary, 0.1),
      rgba(@secondary, 0.1)
    );
    border-radius: 10px;
    border: 1px solid rgba(255, 255, 255, 0.1);
    box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.05);
    transition: all 0.3s ease;
  }

  &:hover::-webkit-scrollbar-thumb {
    background: linear-gradient(
      to bottom,
      rgba(@primary, 0.2),
      rgba(@secondary, 0.2)
    );
    box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.1);
  }

  &::-webkit-scrollbar-thumb:active {
    background: linear-gradient(
      to bottom,
      rgba(@primary, 0.3),
      rgba(@secondary, 0.3)
    );
  }

  scrollbar-width: thin;
  scrollbar-color: rgba(@primary, 0.2) transparent;
}

.panel-header {
  margin-bottom: 2rem;

  .header-content {
    margin-bottom: 1.5rem;

    .panel-title {
      margin: 0;
      font-size: 1.75rem;
      font-weight: 700;
      color: @gray-900;
      position: relative;
      padding-left: 1rem;

      &::before {
        content: "";
        position: absolute;
        left: 0;
        top: 0;
        bottom: 0;
        width: 4px;
        background: linear-gradient(to bottom, @primary, @secondary);
        border-radius: 2px;
      }
    }

    .panel-subtitle {
      margin: 0.5rem 0 0;
      font-size: 0.9375rem;
      color: @gray-500;
    }
  }
}

.btn-open-modal {
  padding: 0.75rem 1.5rem;
  background: linear-gradient(135deg, @primary, @secondary);
  color: white;
  border: none;
  border-radius: 8px;
  font-weight: 500;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  transition: all 0.2s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
  }

  i {
    font-size: 1rem;
  }
}

@media (max-width: 480px) {
  .data-panel {
    padding: 1.25rem;
  }

  .panel-header {
    .header-content {
      .panel-title {
        font-size: 1.5rem;
      }
    }
  }
}
</style>
